/******************************************************************************
* Copyright (C) 2017, Huada Semiconductor Co.,Ltd All rights reserved.
*
* This software is owned and published by:
* Huada Semiconductor Co.,Ltd ("HDSC").
*
* BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND
* BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT.
*
* This software contains source code for use with HDSC
* components. This software is licensed by HDSC to be adapted only
* for use in systems utilizing HDSC components. HDSC shall not be
* responsible for misuse or illegal use of this software for devices not
* supported herein. HDSC is providing this software "AS IS" and will
* not be responsible for issues arising from incorrect user implementation
* of the software.
*
* Disclaimer:
* HDSC MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE,
* REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS),
* ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED
* WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED
* WARRANTY OF NONINFRINGEMENT.
* HDSC SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT,
* NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION,
* LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR
* INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA,
* SAVINGS OR PROFITS,
* EVEN IF Disclaimer HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR
* INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED
* FROM, THE SOFTWARE.
*
* This software may be replicated in part or whole for the licensed use,
* with the restriction that this Disclaimer and Copyright notice must be
* included with each copy of this software, whether used in part or whole,
* at all times.
*/
/******************************************************************************/
/** \file main.c
 **
 ** A detailed description is available at
 ** @link Sample Group Some description @endlink
 **
 **   - 2017-10-31  1.0  Lux First version
 **
 ******************************************************************************/

/******************************************************************************
 * Include files
 ******************************************************************************/
#include "hc32l110.h"
#include "uart.h"
#include "bt.h"
#include "lpm.h"
#include "gpio.h"
#include "adc.h"






/******************************************************************************
 * Global variable definitions (declared in header file with 'extern')
 ******************************************************************************/

/******************************************************************************
 * Local type definitions ('typedef')                                         
 ******************************************************************************/

/******************************************************************************
 * Local function prototypes ('static')
 ******************************************************************************/

/******************************************************************************
 * Local variable definitions ('static')                                      *
 ******************************************************************************/

/******************************************************************************
 * Local pre-processor symbols/macros ('#define')                             
 ******************************************************************************/

void AdcContIrqCallback(void);
void app_timer_start();
void app_timer_stop();




void EnterDeepSleep(void){
	app_timer_stop();

    Clk_SetFunc(ClkFuncWkupRCH, TRUE);
    SCB->SCR |= 0x4;       //sleepdeep
    __NOP();
    __NOP();
    __NOP();
    __NOP();
    __NOP();


	//Lpm Cfg
	 //stcLpmCfg.enSEVONPEND	 = SevPndDisable;
	 //stcLpmCfg.enSLEEPDEEP	 = SlpDpEnable;
	 //stcLpmCfg.enSLEEPONEXIT = SlpExtDisable;
	 //Lpm_Config(&stcLpmCfg);
	__NOP();
	__NOP();
	__NOP();
	__NOP();

	//进入休眠...
	
    __WFI();

    //退出休眠...

    app_timer_start();
}






#define TEST_PIN_EX	(2)
void led_test(){
	//GPIO输入
   //配置P33为输入，P33外接SW2按键
 //  Gpio_InitIO(3, 3, GpioDirIn);
   //如果按键SW2按下，为低电平，则跳出循环继续执行程序
  // while (TRUE == Gpio_GetIO(3,3));   
  
   //GPIO输出
   //初始化外部GPIO P03为输出、上拉、开漏，P03端口外接LED3
   Gpio_InitIOExt(0, TEST_PIN_EX, GpioDirOut, TRUE, FALSE, TRUE, FALSE);
   //设置GPIO值（翻转）
   while (1)
   {
	   //输出高电平，LED3灭
	   Gpio_SetIO(0, TEST_PIN_EX, TRUE);
	   delay1ms(500);

	   //输出低电平，LED3亮
	   Gpio_SetIO(0, TEST_PIN_EX, FALSE);
	   delay1ms(500);
   }

}



#define NextStep()          { while (TRUE == Gpio_GetIO(3,3));\
                                delay1ms(2000);\
                            }

#define SK_LED_INIT()       Gpio_InitIO(0, 3, GpioDirOut)
#define SK_LED_SET(x)       Gpio_SetIO(0,3,(x))


void Gpio_IRQHandler(uint8_t u8Param)
{
    *((uint32_t *)((uint32_t)&M0P_GPIO->P0ICLR + u8Param * 0x40)) = 0;
}


#define SK_SW2_INIT()       Gpio_InitIO(3, 3, GpioDirIn)
#define SK_SW2_GET()        Gpio_GetIO(3,3)

void key_test(){
    //警告！！！为防止程序进入低功耗无法调试，请勿删除以下两行代码
    //SK_SW2_INIT();
    //SK_LED_INIT();
    //SK_LED_SET(0);
    //NextStep();

   // SK_LED_INIT();
    //SK_LED_SET(1);

    //配置P33（SW2）为中断输入端口，下降沿触发
    //Gpio_InitIOExt(3, 3, GpioDirIn, TRUE, FALSE, FALSE, FALSE);
    //Gpio_EnableIrq(3, 3, GpioIrqFalling);
    //
    //EnableNvic(PORT3_IRQn, DDL_IRQ_LEVEL_DEFAULT, TRUE);

    //M0P_GPIO->CTRL0_f.IESEL = 1;

    //Clk_SetFunc(ClkFuncWkupRCH, TRUE);
#if 0
    Clk_SetFunc(ClkFuncWkupRCH, TRUE);
    SCB->SCR |= 0x4;       //sleepdeep
    __NOP();
    __NOP();
    __NOP();
    __NOP();
    __NOP();
#endif
    while (1)
    {
        SK_LED_SET(1);
        delay1ms(500);
        SK_LED_SET(0);
        delay1ms(100);
       // __WFI();
       EnterDeepSleep();
    }
}

#define FLAG_SET	(0x10000)

volatile uint32_t sys_tick_cnt = 0;
volatile uint32_t Flag200ms = 0; 
volatile uint32_t Flag500ms = 0;
volatile uint32_t Flag1000ms = 0;
volatile uint32_t Flag2000ms = 0;
void SysTick_Handler(void)
{

}

//系统时钟
void SysTick_init(void){
	stc_clk_systickcfg_t stcCfg;

	stcCfg.enClk = ClkRCH;          //hclk/8
	stcCfg.u32LoadVal = Clk_GetHClkFreq()/1000 - 1;     //1ms

	Clk_SysTickConfig(&stcCfg);
	SysTick_Config(stcCfg.u32LoadVal);
}

//
void key_init(void){
	//配置P33（SW2）为中断输入端口，下降沿触发
	Gpio_InitIOExt(3, 3, GpioDirIn, TRUE, FALSE, FALSE, FALSE);
	Gpio_EnableIrq(3, 3, GpioIrqFalling);

	EnableNvic(PORT3_IRQn, DDL_IRQ_LEVEL_DEFAULT, TRUE);

	M0P_GPIO->CTRL0_f.IESEL = 1;
}






uint32_t	adc_index = 0;
en_adc_samp_ch_sel_t ADC_CH[3] = {
	AdcExInputCH4,
	AdcExInputCH5,
	AdcExInputCH6 
};


void switch_adc_chanel(en_adc_samp_ch_sel_t ch){
	if (ch > AdcExInputCH8)
		return;
		
	M0P_ADC->CR0_f.SEL = ch;
	M0P_ADC->CR2 = 1<<ch;


}

uint32_t u32AdcResultAcc;
void AdcContIrqCallback(void)
{    
    //中断标志位判断和清零，已在库函数中处理Adc_IRQHandler();
  
    Adc_GetAccResult(&u32AdcResultAcc);
    Adc_ClrAccResult();  

    adc_index = (adc_index + 1)%3;
    switch_adc_chanel(ADC_CH[adc_index]);
}


void adc_init(void){
    stc_adc_cfg_t             stcAdcCfg;
    stc_adc_cont_cfg_t        stcAdcContCfg;
    stc_adc_irq_t             stcAdcIrq;
    stc_adc_irq_calbakfn_pt_t stcAdcIrqCalbaks;
    
    
    DDL_ZERO_STRUCT(stcAdcCfg);
    //DDL_ZERO_STRUCT(stcAdcContCfg);
    DDL_ZERO_STRUCT(stcAdcIrq);
    DDL_ZERO_STRUCT(stcAdcIrqCalbaks);
    
       
    if (Ok != Clk_SetPeripheralGate(ClkPeripheralAdcBgr, TRUE))  //ADCBGR 外设时钟使能
    {
        return ;
    }    

    Gpio_SetAnalog(3, 4, TRUE);

     //ADC配置
    Adc_Enable();
    M0P_BGR->CR_f.BGR_EN = 0x1u;  //BGR必须使能
    M0P_BGR->CR_f.TS_EN = 0x0u;   //内置温度传感器，视使用需求
    delay100us(1);
    
    stcAdcCfg.enAdcOpMode = AdcContMode;                //连续采样模式
    stcAdcCfg.enAdcClkSel = AdcClkSysTDiv1;             //PCLK
    stcAdcCfg.enAdcSampTimeSel = AdcSampTime8Clk;       //8个采样时钟
    // stcAdcCfg.enAdcRefVolSel = RefVolSelInBgr2p5;    //参考电压:内部2.5V(avdd>3V,SPS<=200kHz)
    stcAdcCfg.enAdcRefVolSel = RefVolSelAVDD;           //参考电压:AVDD
    // stcAdcCfg.bAdcInBufEn = TRUE;
    stcAdcCfg.bAdcInBufEn = FALSE;                      //电压跟随器如果使能，SPS采样速率 <=200K
    stcAdcCfg.enAdcTrig0Sel = AdcTrigDisable;           //ADC转换自动触发设置
    stcAdcCfg.enAdcTrig1Sel = AdcTrigDisable;
    Adc_Init(&stcAdcCfg);    
    
    stcAdcIrq.bAdcIrq = TRUE;                            //转换完成中断函数入口配置使能
    stcAdcIrq.bAdcRegCmp = FALSE;
    stcAdcIrq.bAdcHhtCmp = FALSE;
    stcAdcIrq.bAdcLltCmp = FALSE;
    stcAdcIrqCalbaks.pfnAdcContIrq = AdcContIrqCallback; //转换完成中断入口函数
    Adc_ConfigIrq(&stcAdcIrq, &stcAdcIrqCalbaks);        //转换中断入口函数配置
    Adc_EnableIrq();                                     //中断使能
    Adc_CmpCfg(&stcAdcIrq);                              //结果比较中断使能/禁止配置
    
	stcAdcContCfg.enAdcContModeCh = AdcExInputCH4;		//通道0 P24
	stcAdcContCfg.u8AdcSampCnt = 0x00u; 				//P24 连续累加次数(次数 = 0x09+1)
	stcAdcContCfg.bAdcResultAccEn = TRUE;				//累加使能
	Adc_ConfigContMode(&stcAdcCfg, &stcAdcContCfg);    
}




void Pherial_init(){

	Clk_SetPeripheralGate(ClkPeripheralGpio, TRUE); 			 //GPIO 外设时钟使能
	//按键初始化
	key_init();
	//adc init
	adc_init();

    SK_SW2_INIT();
    SK_LED_INIT();
    SK_LED_SET(0);
    NextStep();


	//Gpio_InitIOExt(0, 3, GpioDirOut, TRUE, FALSE, TRUE, FALSE);
	
}

uint8_t	led_state = 0;


void clk24m_init(){
    //RCH 24MHz
    stc_clk_config_t stcClkCfg;
    stcClkCfg.enClkSrc  = ClkRCH;
    stcClkCfg.enHClkDiv = ClkDiv1;
    stcClkCfg.enPClkDiv = ClkDiv1;
	Clk_Init(&stcClkCfg);
   
    Clk_SwitchTo(ClkRCL);
    Clk_SetRCHFreq(ClkFreq24Mhz);
    Clk_SwitchTo(ClkRCH);

}



void app_timer_start(){
	Bt_Run(TIM1);

}

void app_timer_stop(){
	Bt_Stop(TIM1);
}

/*******************************************************************************
 * BT1中断服务函数
 ******************************************************************************/
void timer1_interrupt(void)
{
    if (TRUE == Bt_GetIntFlag(TIM1))
    {
        Bt_ClearIntFlag(TIM1);
        //u32BtTestFlag = 0x02;
		sys_tick_cnt++;
		if (!(Flag200ms&FLAG_SET) &&  Flag200ms++ > 199){
			Flag200ms |= FLAG_SET;
		}

		if (!(Flag500ms&FLAG_SET) &&  Flag500ms++ > 499){
			Flag500ms |= FLAG_SET;
		}

		if (!(Flag1000ms&FLAG_SET) &&  Flag1000ms++ > 999){
			Flag1000ms |= FLAG_SET;
		}
		
		if (!(Flag2000ms&FLAG_SET) &&  Flag2000ms++ > 1999){
			Flag2000ms |= FLAG_SET;
		}


		if (sys_tick_cnt > 5000){
		
			sys_tick_cnt = 0;
			EnterDeepSleep();
		}
    }
}




/*******************************************************************************
 * BT定时功能测试 （重载模式）
 ******************************************************************************/
en_result_t SystemTimerInit(void)
{
    stc_bt_config_t   stcConfig;
    en_result_t       enResult = Error;
    uint16_t          u16ArrData = 0xffff- 1500;
    uint16_t          u16InitCntData = 0xffff- 1500;
    
    stcConfig.pfnTim1Cb = timer1_interrupt;
    //P25设置为门控使能IO
   // Gpio_SetFunc_TIM1_GATE_P25();
        
    stcConfig.enGateP = BtPositive;
    stcConfig.enGate  = BtGateDisable;
    stcConfig.enPRS   = BtPCLKDiv16;
    stcConfig.enTog   = BtTogDisable;
    stcConfig.enCT    = BtTimer;
    stcConfig.enMD    = BtMode2;
    //Bt初始化
    if (Ok != Bt_Init(TIM1, &stcConfig))
    {
        enResult = Error;
    }
    
    //TIM1中断使能
    Bt_ClearIntFlag(TIM1);
    Bt_EnableIrq(TIM1);
    EnableNvic(TIM1_IRQn, 3, TRUE);
    
    //设置重载值和计数值，启动计数
    Bt_ARRSet(TIM1, u16ArrData);
    Bt_Cnt16Set(TIM1, u16InitCntData);
    //Bt_Run(TIM1);
    
    return enResult;
}


void timer_init(){ 
    //打开GPIO、BT外设时钟
	Clk_SetPeripheralGate(ClkPeripheralBt, TRUE);

	SystemTimerInit();

}






/*****************************************************************************
 * Function implementation - global ('extern') and local ('static')
 ******************************************************************************/
/**
 ******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 ******************************************************************************/
int32_t main(void)
{

	/* 时钟 */
	clk24m_init();

	
	timer_init();
	
	//key_test();
	/* 外设：按键，adc */
	Pherial_init();

	//SysTick_init();

	
	key_test();
	
	while(1){
		//Uart_SendData(UARTCH1, 0x12);
		//Uart_SendData(UARTCH1, '2');
		if (Flag200ms & FLAG_SET){
			Flag200ms = 0;

		}
		
		if (Flag500ms & FLAG_SET){
			Flag500ms = 0;

			//if (led_state)
			Gpio_SetIO(0, 3, led_state);
			led_state = ~led_state;

		}
		
		if (Flag1000ms & FLAG_SET){
			Flag1000ms = 0;
			//Adc_Start();		//ADC开始转换	
		}
		
		if (Flag2000ms & FLAG_SET){
			Flag2000ms = 0;
		}
	}
}

/******************************************************************************
 * EOF (not truncated)
 ******************************************************************************/


